package com.tanhua.app.service;

import cn.hutool.core.collection.CollUtil;
import com.itheima.model.dto.OptionsDto;
import com.itheima.model.pojo.Character;
import com.itheima.model.pojo.*;
import com.itheima.model.vo.*;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.dubbo.api.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TestSoulService {

    @DubboReference
    private QuestionnaireApi questionnaireApi;

    @DubboReference
    private QuestionsApi questionsApi;

    @DubboReference
    private OptionsApi optionsApi;

    @DubboReference
    private ReportApi reportApi;

    @DubboReference
    private CharacterApi characterApi;

    @DubboReference
    private DimensionApi dimensionApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserLockApi userLockApi;

    // 问卷列表
    public List<QuestionnaireVo> testSoul() {
        // 查询所有的问卷数据
        List<Questionnaire> questionnaireList = questionnaireApi.findAll();

        // 判断是否有问卷
        if (CollUtil.isEmpty(questionnaireList)) {
            throw new BusinessException(ErrorResult.questionnaireError());
        }

        // 分装问卷数据
        List<QuestionnaireVo> list = new ArrayList<>();
        for (Questionnaire questionnaire : questionnaireList) {
            QuestionnaireVo vo = QuestionnaireVo.init(questionnaire);

            // 根据问卷id，查询试题数据
            List<Questions> questionsList = questionsApi.findByQuestionnaireId(questionnaire.getId());

            if (CollUtil.isEmpty(questionsList)) {
                throw new BusinessException(ErrorResult.questionsError());
            }

            // 遍历试题列表，获取试题对应的选项
            List<QuestionsVo> questionsVos = new ArrayList<>();
            for (Questions question : questionsList) {
                // 获取试题对应的选项数据
                List<Options> optionsList = optionsApi.findByQuestionId(question.getId());

                if (CollUtil.isEmpty(optionsList)) {
                    throw new BusinessException(ErrorResult.optionsError());
                }

                // 分装选项数据
                List<OptionsVo> optionsVos = optionsList.stream().map(OptionsVo::init).collect(Collectors.toList());

                // 分装试题数据
                QuestionsVo questionsVo = QuestionsVo.init(question);
                questionsVo.setOptions(optionsVos);

                questionsVos.add(questionsVo);
            }

            vo.setQuestions(questionsVos);

            // 获取锁数据
            UserLock userLock = userLockApi.findByUserIdAndQuestionnaireId(UserHolder.getUserId(), questionnaire.getId());
            if (userLock == null) {
                // 添加数据
                userLock = new UserLock();
                userLock.setUserId(UserHolder.getUserId());
                userLock.setQuestionnaireId(questionnaire.getId());
                // 给排序为1的问卷解锁
                if (questionnaire.getSort().equals(1)) {
                    userLock.setIsLock(0);
                } else {
                    userLock.setIsLock(1);
                }
                userLockApi.save(userLock);
            }

            vo.setIsLock(userLock.getIsLock());

            // 分装报告Id
            // 根据当前用户Id和问卷id，查询出报告数据
            Report report = reportApi.findByUserIdAndQuestionnaireId(UserHolder.getUserId(), questionnaire.getId());
            if (report == null) {
                // 如果报告id，不存在
                vo.setReportId(null);
            } else {
                // 报告存在
                vo.setReportId(report.getId().toString());
            }


            list.add(vo);
        }

        return list;
    }

    // 提交问卷
    public String save(List<OptionsDto> answers) {

        // 根据 试题id和选项id获取，获取具体的选项对象
        Integer sum = 0;
        for (OptionsDto answer : answers) {
            Options options = optionsApi.findByIdAndQuestionId(answer);
            // 获取总分
            sum += options.getScore();
        }

        // 根据任意试题编号，获取问卷Id
        Questions questions = questionsApi.findById(answers.get(0).getQuestionId());

        // 根据总分算出类型
//        10-20：狐狸型，21-40分：狮子型，41-60：白兔型
        int flag = 0;
        if (sum >= 10 && sum <= 20) {
            flag = 2;
        } else if (sum <= 40) {
            flag = 3;
        } else if (sum <= 60) {
            flag = 4;
        } else {
            flag  = 1;
        }

        // 根据标识，获得人格类型
        Character character = characterApi.findBySign(flag);

        // 根据当前用户id和问卷id,查询报告表
        Report report = reportApi.findByUserIdAndQuestionnaireId(UserHolder.getUserId(), questions.getQuestionnaireId());
        if (report == null) {
            // 数据不存在，保存数据
            // 分装数据
            report = new Report();
            report.setSum(sum);
            report.setQuestionnaireId(questions.getQuestionnaireId());
            report.setUserId(UserHolder.getUserId());
            report.setCharacterId(character.getId());
            // 保存数据
            Long reportId = reportApi.save(report);
            report.setId(reportId);

            // 根据用户id和问卷id获取锁
            UserLock userLock = userLockApi.findByUserIdAndQuestionnaireId(UserHolder.getUserId(), questions.getQuestionnaireId());
            Questionnaire questionnaire = questionnaireApi.findById(userLock.getQuestionnaireId());
            // 获取下一级问卷
            questionnaire = questionnaireApi.findBySort(questionnaire.getSort() + 1);
            // 判断是否还有下一级问卷
            if (questionnaire != null) {
                // 解锁下一级问卷
                userLock = userLockApi.findByUserIdAndQuestionnaireId(UserHolder.getUserId(), questionnaire.getId());
                userLock.setIsLock(0);

                // 修改锁数据
                userLockApi.update(userLock);
            }

        } else {
            // 数据存在，修改分数和类型id
            report.setCharacterId(character.getId());
            report.setSum(sum);

            // 修改报告表中的人格类型数据
            reportApi.update(report);
        }

        return report.getId().toString();
    }

    //查看结果
    public CharacterVo findCharacter(Long id) {

        // 根据报告Id查询报告数据
        Report report = reportApi.findById(id);

        if (report == null) {
            // 证明用户没有测试,跳转转到测试页面
            return null;
        }

        // 根据人格类型Id，查询人格
        Character character = characterApi.findById(report.getCharacterId());

        // 根据人类类型id查询维度列表
        List<DimensionVo> dimensionList = dimensionApi.findByCharacterId(character.getId())
                .stream().map(DimensionVo::init).collect(Collectors.toList());

        // 根据当前人格类型id，查询报告表，抽取用户id
        List<Long> userIds = reportApi.findByCharacter(character.getId()).stream()
                .map(Report::getUserId)
                .collect(Collectors.toList());

        // 查询相似用户，过滤掉当前用户
        List<UserInfo> userInfos = userInfoApi.findByUserIds(userIds)
                .stream().filter(userInfo -> !userInfo.getId().equals(UserHolder.getUserId()))
                .collect(Collectors.toList());


        // 封装数据
        CharacterVo vo = new CharacterVo();
        vo.setConclusion(character.getConclusion());
        vo.setCover(character.getCover());
        vo.setDimensions(dimensionList);
        vo.setSimilarYou(userInfos);

        return vo;
    }
}
